from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import UserManager,AbstractUser
from taskhero import settings

    
# Create your models here.

class AppUser(AbstractUser):

    experience_made = models.IntegerField(default=0)
    experience_needed = models.IntegerField(default=100)
    level = models.IntegerField(default=1)     
    
    def award_experience(self, exp_to_award):
        self.experience_made += exp_to_award
        if self.experience_made == self.experience_needed:
            self._level()
        elif self.experience_made > self.experience_needed:
            offset = self.experience_made - self.experience_needed
            self._level(offset)
        self.save()

    def remove_experience(self, exp_to_remove):
        self.experience_made -= exp_to_remove
        if self.experience_made < 0:
            self.experience_made = 0
        self.save()

    def _level(self, offset=None):
        if offset:
            self.experience_made = offset
        else:
            self.experience_made = 0
        self.level += 1
        self.experience_needed = self.experience_needed * 2
        self.save()

    

class Task(models.Model):
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now_add=True, auto_now=True)
    title = models.CharField(max_length=100)
    body = models.TextField()
    list = models.ForeignKey('TaskList')
    DIFFICULTY_CHOICES = (
        ('E', 'Easy'),
        ('M', 'Medium'),
        ('H', 'Hard'),
        ('EP', 'Epic'),
    )
    difficulty = models.CharField(max_length=2, choices=DIFFICULTY_CHOICES)
    experience_reward = models.IntegerField(null=True, blank=True)
    completed = models.BooleanField(default=False)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL)
    due_date = models.DateTimeField()

    def __unicode__(self):
        return self.title

    def figure_experience_points(self):
        if self.difficulty == 'E':
            exp = 25
        elif self.difficulty == 'M':
            exp = 50
        elif self.difficulty == 'H':
            exp = 100
        elif self.difficulty == 'EP':
            exp = 200
        self.experience_reward = exp
        self.save()
        return self.experience_reward


    def complete(self):
        self.owner.award_experience(self.experience_reward)
        self.completed = True
        self.save()


    
class TaskList(models.Model):

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now_add=True, auto_now=True)
    title = models.CharField(max_length=100)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL)
    description = models.CharField(max_length=200)
    

    def __unicode__(self):
        return self.title

    def get_tasks(self):
        tasks = Task.objects.filter(list=self.id)
        return tasks



